import 'package:flutter/material.dart';

import '../model/comment.dart';

typedef OnReplyCallback = void Function(Comment comment);

class CommentItem extends StatelessWidget {
  final Comment comment;
  final OnReplyCallback onReply;
  final bool isReply;

  const CommentItem({
    Key? key,
    required this.comment,
    required this.onReply,
    this.isReply = false,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final avatarSi_buildRepliesze = 40.0;

    return Padding(
      padding: EdgeInsets.only(
        left: isReply ? 56 : 16,
        right: 16,
        top: 12,
        bottom: 4,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 主评论
          _buildCommentTile(context, comment, isReply: isReply),

          // 子评论（只展示一层，不递归）
          if (comment.replies.isNotEmpty)
            Padding(
              padding: const EdgeInsets.only(top: 8),
              child: Column(children: _buildReplies(comment)),
            ),
        ],
      ),
    );
  }

  Widget _buildCommentTile(
    BuildContext context,
    Comment c, {
    required bool isReply,
  }) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        ClipOval(
          child: Image.network(
            c.avatar,
            width: 40,
            height: 40,
            fit: BoxFit.cover,
          ),
        ),
        const SizedBox(width: 12),
        Expanded(
          child: GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () => onReply(c),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  c.username,
                  style: const TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 14,
                  ),
                ),
                const SizedBox(height: 4),
                Row(
                  children: [
                    Expanded(
                      child: Text(
                        c.content,
                        style: const TextStyle(fontSize: 14),
                      ),
                    ),
                    const SizedBox(width: 8),
                    Text(
                      timeAgo(c.createdAt),
                      style: const TextStyle(fontSize: 12, color: Colors.grey),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildReplyTile(
    BuildContext context,
    Comment reply, {
    required String parentUsername,
  }) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () => onReply(reply),
      child: Padding(
        padding: const EdgeInsets.only(left: 48),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text.rich(
              TextSpan(
                children: [
                  TextSpan(
                    text: reply.username,
                    style: const TextStyle(fontWeight: FontWeight.bold),
                  ),
                  const TextSpan(text: ' 回复 '),
                  TextSpan(
                    text: parentUsername,
                    style: const TextStyle(fontWeight: FontWeight.bold),
                  ),
                  const TextSpan(text: '：'),
                  TextSpan(text: reply.content),
                ],
              ),
            ),
            const SizedBox(height: 2),
            Text(
              timeAgo(reply.createdAt),
              style: const TextStyle(fontSize: 12, color: Colors.grey),
            ),
          ],
        ),
      ),
    );
  }

  List<Widget> _buildReplies(Comment rootComment) {
    final List<_ReplyChain> flatReplies = [];

    for (final reply in rootComment.replies) {
      _flattenReplies(reply, rootComment.username, flatReplies);
    }

    return flatReplies.map((r) {
      return Padding(
        padding: const EdgeInsets.only(left: 48, top: 8),
        child: GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () => onReply(r.comment),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text.rich(
                TextSpan(
                  children: [
                    TextSpan(
                      text: r.comment.username,
                      style: const TextStyle(fontWeight: FontWeight.bold),
                    ),
                    const TextSpan(text: ' 回复 '),
                    TextSpan(
                      text: r.replyTo,
                      style: const TextStyle(fontWeight: FontWeight.bold),
                    ),
                    const TextSpan(text: '：'),
                    TextSpan(text: r.comment.content),
                  ],
                ),
              ),
              const SizedBox(height: 2),
              Text(
                timeAgo(r.comment.createdAt),
                style: const TextStyle(fontSize: 12, color: Colors.grey),
              ),
            ],
          ),
        ),
      );
    }).toList();
  }
}

// 时间转换函数
String timeAgo(String isoTime) {
  final dateTime = DateTime.parse(isoTime);
  final now = DateTime.now();
  final diff = now.difference(dateTime);

  if (diff.inMinutes < 1) return '刚刚';
  if (diff.inMinutes < 60) return '${diff.inMinutes}分钟前';
  if (diff.inHours < 24) return '${diff.inHours}小时前';
  if (diff.inDays == 1) return '昨天';
  if (diff.inDays == 2) return '前天';
  if (diff.inDays <= 7) return '${diff.inDays}天前';
  return '${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')}';
}

void _flattenReplies(
  Comment comment,
  String replyTo,
  List<_ReplyChain> result,
) {
  result.add(_ReplyChain(comment: comment, replyTo: replyTo));
  for (final child in comment.replies) {
    _flattenReplies(child, comment.username, result);
  }
}

class _ReplyChain {
  final Comment comment;
  final String replyTo;

  _ReplyChain({required this.comment, required this.replyTo});
}
